package com.example.impala.csv;

import com.cloudera.impala.jdbc41.internal.com.cloudera.altus.shaded.org.apache.commons.lang3.ArrayUtils;
import com.cloudera.impala.jdbc41.internal.com.cloudera.altus.shaded.org.apache.commons.lang3.RandomStringUtils;
import com.cloudera.impala.jdbc41.internal.com.cloudera.altus.shaded.org.apache.commons.lang3.StringUtils;
import com.example.impala.jdbc.Jdbc;
import com.example.impala.model.ImpalaArg;
import javafx.scene.text.FontBuilder;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
import org.apache.commons.csv.QuoteMode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author: LiuJie
 * @Date: 2019-06-22 23:57
 * @Description:
 */
@Component
public class CsvUtil {

    @Value("${project.file-path}")
    private String filePath;
    public static ConcurrentHashMap<String, String> argCsvNameMap = new ConcurrentHashMap<>();

    @Autowired
    private Jdbc jdbc;

    public byte[] dataPersistence(String argString, List<Map<String, Object>> rlt) {
        try {
            String csvStr = exportRltMapToCsv(rlt);
            byte[] fileByte = csvStr.getBytes(Charset.forName("UTF-8"));
            byte[] bom = new byte[]{(byte) 0xEF, (byte) 0xBB, (byte) 0xBF};
            byte[] fileByteBom = ArrayUtils.addAll(bom, fileByte);
            String fileName = RandomStringUtils.randomAlphanumeric(12) + ".csv";
            String file = filePath + fileName;
            Path path = Paths.get(file);
            Files.write(path, fileByteBom);
            argCsvNameMap.put(argString, file);
            return fileByteBom;
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
    }

    public String exportRltMapToCsv(List<Map<String, Object>> rlt) throws IOException {
        Set<String> ths = rlt.get(0).keySet();
        StringBuilder stringBuilder = new StringBuilder();
        String[] thArray = ths.toArray(new String[ths.size()]);
        CSVPrinter printer = new CSVPrinter(stringBuilder, CSVFormat.DEFAULT.withQuoteMode(QuoteMode.ALL_NON_NULL).withHeader(thArray));
        for (Map<String, Object> row : rlt) {
            printer.printRecord(row.values());
        }
        return stringBuilder.toString();
    }

    public byte[] readFileByArg(ImpalaArg arg) {
        synchronized (arg.toString()) {
            String file = argCsvNameMap.get(arg.toString());
            if (StringUtils.isNoneBlank(file)) {
                File file1 = new File(file);
                if (!file1.exists()) {
                    throw new RuntimeException("系统异常文件不存在");
                }
                Path path = Paths.get(file);
                try {
                    return Files.readAllBytes(path);
                } catch (IOException e) {
                    e.printStackTrace();
                    throw new RuntimeException(e.getMessage());
                }

            } else {
                List list = jdbc.executeJdbc(arg);
                return dataPersistence(arg.toString(), list);
            }

        }
    }
}
